package com.ct.ecommerce.framework.security;

import com.ct.ecommerce.framework.constant.SecurityConstants;
import java.util.Map;
import java.util.Objects;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;

/**
 * @author changtong
 * @since 2021/6/1
 */
public final class SecurityContextHolderUtils {

    private SecurityContextHolderUtils() {
    }

    public static boolean isAuthenticated() {
        OAuth2Authentication authentication = (OAuth2Authentication) SecurityContextHolder
            .getContext().getAuthentication();
        return authentication.isAuthenticated();
    }

    public static UserWrapperDTO getUser() {
        OAuth2Authentication authentication = (OAuth2Authentication) SecurityContextHolder
            .getContext().getAuthentication();
        if (authentication.isAuthenticated()) {
            Map<String, Object> info =
                authentication.getPrincipal() instanceof Map ? ((Map<String, Object>) authentication
                    .getPrincipal()) : null;
            if (Objects.nonNull(info)) {
                UserWrapperDTO user = new UserWrapperDTO();
                user.setUserId(Long.valueOf((String) info.get(SecurityConstants.ID_FIELD)));
                user.setUserName((String) info.get(SecurityConstants.USER_NAME));
                return user;
            }
        }
        return null;
    }
}
